<template>
  <div style="background: #EEEEEE7F; height: 100vh; display: flex; flex-direction: column;">
    <van-nav-bar
        title="选择仪器"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />
    <!-- 搜索框 -->
    <van-search v-model="searchValue" placeholder="请输入仪器名称" />
    <van-tree-select
        v-model:main-active-index="activeIndex"
        :items="items"
        style="flex: 1; overflow-y: auto;"
    >
      <template #content>
        <div v-if="filteredGroups && filteredGroups[items[activeIndex]?.text]">
          <template v-for="group in getGroupsByType(items[activeIndex].text)" :key="group.name">
            <van-divider :style="{ color: '#a0a3a2', borderColor: '#a0a3a2', padding: '0 16px' }">{{ group.name }}</van-divider>
            <van-grid :column-num="3">
              <van-grid-item
                  v-for="instrument in group.instruments"
                  :key="instrument.id"
                  :text="instrument.name"
                  @click="onClickItem(instrument)"
              >
                <template #icon>
                  <img
                      :src="`/api/src/img/${instrument.imgName}`"
                      style="width: 60px; height: 60px; object-fit: contain;"
                      alt="instrument image"
                  />
                </template>
              </van-grid-item>
            </van-grid>
          </template>
        </div>
        <div v-else style="padding: 16px; color: #999;">
          当前分类暂无数据
        </div>
      </template>
    </van-tree-select>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getInstruments } from '@/apps/client/utils/instrumentApi';
import { toPage } from '@/apps/client/utils/routerUtil';

const searchValue = ref('');
const activeIndex = ref(0);
// 分组
const items = ref([
  { text: "科研仪器" },
  { text: "教学仪器" },
  { text: "通用仪器" },
  { text: "专用仪器" }
]);

const groups = ref({});

// 过滤后的分组，根据searchValue过滤仪器名称
const filteredGroups = computed(() => {
  if (!searchValue.value.trim()) {
    // 搜索为空，返回全部
    return groups.value;
  }

  const keyword = searchValue.value.trim().toLowerCase();

  const result = {};

  // 遍历 groups，每个类型下的组过滤
  Object.keys(groups.value).forEach(typeName => {

    const filteredGroupList = groups.value[typeName]
        .map(group => {
          // 过滤该组的 instruments
          const filteredInstruments = group.instruments.filter(inst => inst.name.toLowerCase().includes(keyword));

          if (filteredInstruments.length > 0) {
            return {
              name: group.name,
              instruments: filteredInstruments
            };
          }
          return null;
        })
        .filter(Boolean);

    if (filteredGroupList.length > 0) {
      result[typeName] = filteredGroupList;
    }
  });

  return result;
});

function getGroupsByType(typeName) {
  // 使用过滤后的数据
  return filteredGroups.value[typeName] || [];
}

const instrumentsGroup = sessionStorage.getItem("instrumentsGroup");
if (!instrumentsGroup) {
  getInstruments().then((body) => {
    groups.value = body.data;
    sessionStorage.setItem("instrumentsGroup", JSON.stringify(body.data));
  });
} else {
  groups.value = JSON.parse(instrumentsGroup);
}

const router = useRouter();
const onClickLeft = () => {
  router.back();
};

function onClickItem(item) {
  console.log('选择了仪器:', item);
  sessionStorage.setItem("selectInstrumentId", item.id);
  const selectInstrumentRoutePage = sessionStorage.getItem("selectInstrumentRoutePage");
  toPage(selectInstrumentRoutePage);
}
</script>

<style scoped>
::v-deep(.van-tree-select__nav-item) {
  white-space: nowrap;
}
</style>
